package com.gdut.multiusercommunicationsystem.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserManager {
    private ConcurrentHashMap<Integer,WebSocketSession> concurrentMap=new ConcurrentHashMap<>();
    public void online(int userId, WebSocketSession session){
        if(concurrentMap.get(userId)!=null){
            System.out.println("该用户已上线");
            return ;
        }
        concurrentMap.put(userId,session);
        System.out.println("["+userId+"]"+"上线");
    }
    public void offline(int userId,WebSocketSession session){
        if(concurrentMap.get(userId) == session){
            concurrentMap.remove(userId);
            System.out.println("["+userId+"]"+"下线");
        }
    }
    //通过userId找session
    public WebSocketSession getSession(int userId){
        return concurrentMap.get(userId);
    }
}
